import { IPageResponse } from "@/common/CommonType";
import { ValidationError } from "@/utils/errors";
import SysUserEntity from "./Entity";
import appDataSource from "@/db";

export class SysRoleService {
  /**
   * 添加数据
   */
  public static async add(data: SysUserEntity): Promise<true> {
    // 1. 转换类型
    data = SysUserEntity.transform(data);
    // 2. 数据验证
    const errors = await data.validateThis();
    if (errors.length > 0) {
      throw new ValidationError(errors[0]);
    }

    const rep = appDataSource.getRepository(SysUserEntity);

    const row = await rep.findBy({ value: data.value });
    if (row.length > 0) {
      throw new ValidationError("value已存在！");
    }

    await rep.save(data);
    return true;
  }

  /**
   * 分页获取数据
   */
  public static async findByPage(current: number, size: number, where?: any): Promise<IPageResponse> {
    const rep = appDataSource.getRepository(SysUserEntity);
    const [list, total] = await rep.findAndCount({
      skip: size * (current - 1),
      take: size,
      where,
    });
    return {
      total,
      list,
    };
  }

  /**
   * 无分页
   */
  public static async findByList(where?: any) {
    const rep = appDataSource.getRepository(SysUserEntity);
    return rep.find({
      where,
    });
  }

  /**
   * 通过id获取数据
   */
  public static async findById(id: string) {
    const rep = appDataSource.getRepository(SysUserEntity);
    return await rep.findOneBy({ id: +id });
  }

  /**
   * 修改数据
   */
  public static async update(data: any) {
    const rep = appDataSource.getRepository(SysUserEntity);
    const result = await rep.update(data.id, data);
    return result.raw;
  }

  /**
   * 删除数据
   */
  public static async delete(id: string) {
    const rep = appDataSource.getRepository(SysUserEntity);
    const result = await rep.softDelete({ id: +id });
    return result.raw;
  }
}
